<template>

  <el-dialog v-model="dialogVisible" title="添加配送信息" width="50%" :before-close="handleClose">
    <el-form ref="refForm" :model="formData" :rules="rule" size="small" class="special-form" label-width="110px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="产品信息：">
            {{ getProductName(datas) }}
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="代理名称：">
            {{ datas?.agentName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="代理地区：">
            <area-list-view :areas="datas?.region" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="可销售终端：">
            {{ getLabel('app_mode', datas.terminalType) }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责营销职员：">
            {{ datas.headName }}
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="配送模式">
            <el-radio v-model="formData.rddType" label="2" size="large" @change="radioChange">配送商配送</el-radio>
            <el-radio v-model="formData.rddType" label="1" size="large" @change="radioChange">厂家配送</el-radio>
          </el-form-item>
        </el-col>

        <el-col v-if="formData.rddType == 2" :span="24">
          <el-form-item label="配送商" prop="distributeId">
            <el-select v-model="formData.distributeId" style="width: 100%" placeholder="请选择配送商"
              @change="distributesChange">
              <el-option v-for="item in distributes" :key="item.id" :label="item.distributeName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-if="formData.rddType == 2" :span="24">
          <el-form-item label="配送费" prop="distributeDetailId">
            <distribute-price-popover ref="pricePopoverRef" :datas="{
                productId: formData.productId,
                distributeId: formData.distributeId,
                region:datas.region,
                agentProductId:datas.id
                }" position="bottom-start" @confirm="selectPrice">
              <div style="display:flex;flex-wrap:nowrap;">
                <el-select v-model="formData.distributePrice" style="flex:1;" placeholder="选择配送费"
                  :disabled="formData.productId&&formData.distributeId?false:true" @focus="priceFocus"
                  @change="distributePriceChange">
                  <template #empty />
                </el-select>
                <div v-if="distributePriceInfo?.computeMode==='固定价格'">
                  <span v-if="formData.sellUnit" style="margin-left:4px;">
                    元 / {{ getLabel('sell_unit',formData.sellUnit) }}
                  </span>
                </div>
                <div v-if="distributePriceInfo?.computeMode==='终端价百分比'">%终端价</div>
              </div>
            </distribute-price-popover>
          </el-form-item>
        </el-col>

      </el-row>

    </el-form>

    <item-title title="配送终端列表">
      <template #btn>
        <el-button class="main-btn delete-btn" size="small" @click="allDelete">全部删除</el-button>
        <el-button class="main-btn" size="small" type="primary" @click="addClick">添加终端</el-button>
      </template>
    </item-title>

    <el-table max-height="300px" border header-cell-class-name="table-header" :data="tableData">
      <el-table-column header-align="center" align="center" label="终端名称" prop="terminalName" />

      <el-table-column header-align="center" align="center" label="终端类型" prop="type">
        <template #default="scope">
          {{ getLabel('app_mode',scope.row.terminalType) }}
        </template>
      </el-table-column>

      <el-table-column header-align="center" align="center" label="所在地区" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.provinceName }}{{ scope.row.cityName }}{{ scope.row.areaName }}
        </template>
      </el-table-column>

      <el-table-column header-align="center" align="center" label="终端价(元)">
        <template #default="scope">
          <div v-if="scope.row.devId !== 0">
            {{scope.row.terminalPrice}}
          </div>
          <app-price-popover v-else :ref="(el)=>{priceProp(el,scope)}" :props-product="scope.row.propData"
            position="top-start" @confirm="(val) => {priceConfirm(val,scope)}">
            <el-select v-model="scope.row.terminalPrice" placeholder="请选择终端价" @focus="refFocus(scope)">
              <template #empty />
            </el-select>
          </app-price-popover>

        </template>
      </el-table-column>

      <el-table-column header-align="center" align="center" label="已有配送信息">
        <template #default="scope">
          <distributors-view v-if="scope.row.distributeContractDetails && scope.row.distributeContractDetails.length"
            :datas="scope.row.distributeContractDetails" :unit="datas.sellUnit" />
        </template>
      </el-table-column>

      <el-table-column header-align="center" align="center" label="操作">
        <template #default="scope">
          <el-button type="text" class="delete-text-btn" @click="onDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" size="small">取消</el-button>
        <el-button type="primary" size="small" @click="dialogConfirm">提交审核</el-button>
      </div>
    </template>
  </el-dialog>

  <addTerminalDialog ref="addTerminal" :list="tableData" @confirm="terminalConfirm" />

</template>

<script>
import {useStore} from "vuex";
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, toRefs,} from "vue";

export default defineComponent({
  name: "TerAndDisDialog",
  emits:['success'],
  components: {
    distributePricePopover: defineAsyncComponent(() =>
      import("./distributePricePopover.vue")
    ),
    addTerminalDialog: defineAsyncComponent(() =>
      import("./addTerminalDialog.vue")
    ),
  },
  setup(props, context) {
    const store = useStore();
    const user = store.getters["user/userInfo"];
    const currentInstance = getCurrentInstance();
    const api = inject("api");
    var data = reactive({
      dialogVisible: false,
      tableData: [],
      formData: {
        productId: 0,
        rddType: "2",
        distributeId: "",
        distributeName: "",
        distributePrice: "",
        distributeDetailId: "",
        sellUnit: "",
      },
      datas: {},
      distributes: [],
      prices: [],
      pricePopoverRef: null,
      distributePriceInfo: null,
      addTerminal: null,
      refForm: null,
      priceRef: {},
    });
    const rule = reactive({
      distributeId: [
        { required: true, message: "请选择配送商", trigger: "change" },
      ],
      distributeDetailId: [
        { required: true, message: "请选择配送服务", trigger: "change" },
      ],
      dd: [{ required: true, message: "请选择配送商", trigger: "change" }],
    });

    const priceProp = (el, scope) => {
      data.priceRef[scope.$index] = el;
    };

    const refFocus = (scope) => {
      data.priceRef[scope.$index].openPopover();
    };

    const priceConfirm = (val, scope) => {
      data.tableData[scope.$index].productPriceId = val.id;
      data.tableData[scope.$index].app_price = val.terminalPrice;
      data.tableData[scope.$index].terminalPrice = Number(val.terminalPrice);
    };

    const onDelete = (scope) => {
      data.tableData.splice(scope.$index, 1);
    };

    const radioChange = () => {
      data.tableData = [];
      data.datas.distributeRegion = [];
      data.formData.distributeId = "";
      data.formData.distributeDetailId = "";
      data.distributePriceInfo = null;
      data.formData.distributePrice = "";
      data.formData.sellUnit = "";
    };

    const handleClose = () => {
      data.formData = {
        productId: 0,
        rddType: "2",
        distributeId: "",
        distributeName: "",
        distributePrice: "",
        distributeDetailId: "",
        distributeServerNo: "",
        sellUnit: "",
      };
      data.tableData = [];

      data.dialogVisible = false;
      setTimeout(() => {
        data.refForm.clearValidate();
      }, 500);
    };

    const dialogConfirm = () => {
      data.refForm.validate((val) => {
        if (val) {
          if (!data.tableData.length) {
            currentInstance.proxy.customMessage({
              type: "error",
              message: "请添加终端",
            });
            return;
          }
          for (let i = 0; i < data.tableData.length; i++) {
            if (!data.tableData[i].productPriceId) {
              currentInstance.proxy.customMessage({
                type: "error",
                message: "请选择终端价",
              });
              return;
            }
          }

          const a = {
            agentProductId: Number(data.datas.id),
            productId: Number(data.datas.productId),
            productName: data.datas.productName,
            productPopularName: data.datas.productPopularName,
            packSpecs: data.datas.packSpecs,
            sellUnit: data.datas.sellUnit,
            rddType: data.formData.rddType,
            distributeId: Number(data.formData.distributeId),
            distributeName: data.formData.distributeName,
            distributeServerId: Number(data.formData.distributeDetailId),
            distributeServerNo: data.formData.distributeServerNo,
            terminalType: data.datas.terminalType,
            headName: user.realName,
            headId: Number(user.ID),
            terminals: data.tableData,
            tradePrice: data.datas.tradePrice,
          };
          api.signedAgent
            .DISTRIBUTE_CONTRACT_DETAIL_ASSOCIATION(a)
            .then((res) => {
              if (!res.code) {
                currentInstance.proxy.customMessage({
                  type: "success",
                  message: "提交成功",
                });
                context.emit("success");
                handleClose();
              } else {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              }
            });
        }
      });
    };

    const getDistributors = () => {
      api.distributors
        .PRODUCT_FOR_DISTRIBUTORS_LIST({
          productId: data.datas.productId,
        })
        .then((res) => {
          if (!res.code) {
            data.distributes = res.data.list;
          }
        });
    };

    const distributesChange = () => {
      const index = data.distributes.findIndex(
        (a) => a.id == data.formData.distributeId
      );
      if (index != -1) {
        data.formData.distributeName = data.distributes[index].distributeName;
      }
      data.formData.distributeDetailId = "";
      data.formData.distributeServerNo = "";
      data.distributePriceInfo = null;
      data.formData.distributePrice = "";
      data.formData.sellUnit = "";
    };

    const priceFocus = (val) => {
      if (val) {
        data.pricePopoverRef.openPopover();
      }
    };

    const distributePriceChange = (val) => {
      console.log(val);
      data.formData.distributeDetailId = "";
      data.formData.distributeServerNo = "";
      data.distributePriceInfo = null;
      data.formData.distributePrice = "";
      data.formData.sellUnit = "";
    };

    const selectPrice = (val) => {
      if (
        val?.id !== data.formData.distributeDetailId &&
        data.formData.distributeDetailId
      ) {
        allDelete();
      }
      console.log(val);

      data.datas.distributeRegion = val?.region;
      data.distributePriceInfo = val;
      data.formData.distributeDetailId = val?.id;
      data.formData.distributeServerNo = val?.distributeServeNo;
      data.formData.distributePrice = val?.distributePrice;
      data.formData.sellUnit = val?.sellUnit;
    };

    const addClick = () => {
      if (data.formData.rddType == 2) {
        Promise.all([
          handlValidateField("distributeId"),
          handlValidateField("distributeDetailId"),
        ]).then(() => {
          data.datas.distributeId = data.formData.distributeId;
          data.addTerminal.openDialog(data.datas);
        });
      }
    };

    const handlValidateField = (val) => {
      return new Promise((resolve, reject) => {
        data.refForm.validateField(val, (valid) => {
          if (!valid) {
            resolve();
          } else {
            return false;
          }
        });
      });
    };

    const allDelete = () => {
      data.tableData = [];
    };

    const terminalConfirm = (list) => {
      const arr = [];
      for (let i = 0; i < list.length; i++) {
        const a = { ...list[i] };
        a.propData = {
          terminalId: a.id,
          terminalType: a.terminalType,
          productId: data.datas.productId,
          region: data.datas.region,
        };
        arr.push(a);
      }
      data.tableData = data.tableData.concat(arr);
    };

    const open = (item) => {
      data.datas = item;
      data.formData.productId = item.productId;
      data.dialogVisible = true;
      getDistributors();
    };

    onMounted(() => {});

    return {
      ...toRefs(data),
      rule,

      handleClose,
      dialogConfirm,
      onDelete,
      open,
      addClick,
      allDelete,
      distributesChange,
      priceFocus,
      distributePriceChange,
      selectPrice,
      terminalConfirm,
      priceProp,
      refFocus,
      priceConfirm,
      radioChange,
    };
  },
});
</script>

<style scoped>
</style>
